package com.kasax.hilog.printer;

import android.text.TextUtils;
import android.util.Log;

import com.kasax.hilog.LogConfig;
import com.kasax.hilog.LogLevel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 打印到文件中
 */
public class FilePrinter implements ILogPrinter {
    private static final String TAG = "KasaxToolbox";

    @Override
    public void log(LogLevel logLevel, LogConfig config, String msg) {
        String cacheDirPath = config.logFileCacheDirPath();
        Log.d(TAG, "cacheDirPath: " + cacheDirPath);
        if (!TextUtils.isEmpty(cacheDirPath)) {
            File dirPath = new File(cacheDirPath);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            if (dirPath.exists()) {
                File logFile = new File(dirPath, "DLog_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +
                        ".log");
                Log.d(TAG, "logFile path: " + logFile.getAbsolutePath());
                Log.d(TAG, "need write msg: " + msg);
                if (!logFile.exists()) {
                    try {
                        logFile.createNewFile();
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
                try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile,
                        true)))) {
                    bw.write(msg);
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "File not found: " + e.getMessage());
                } catch (IOException e) {
                    Log.e(TAG, "IO error: " + e.getMessage());
                }
            }
        }
    }
}
